package com.py.credit.controller;

import com.py.credit.common.XypjConstants;
import com.py.credit.entity.Enterprise;
import com.py.credit.entity.GatewayUserEntity;
import com.py.credit.service.CardsService;
import com.py.credit.service.GatewayAuthenticationService;
import com.py.credit.service.GatewayUserService;
import com.py.credit.service.XypjRemoteBaseService;
import com.py.credit.utils.UuidUtil;
import com.py.framework.core.helper.HttpServletHelper;
import com.py.framework.core.helper.JWTHelper;
import com.py.framework.core.log.ExceptionLogger;
import com.py.framework.core.rest.support.RestServiceResult;
import com.py.framework.core.utils.BeanUtil;
import com.py.framework.core.utils.DateUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 信用评价前台网站用户登录注册Controller
 */
@RestController
@RequestMapping("/xypjUser")
public class GatewayLoginController extends GatewaySystemController {

    @Autowired
    private GatewayUserService gatewayUserService;

    @Autowired
    private GatewayAuthenticationService gatewayAuthenticationService;

    @Autowired
    private XypjRemoteBaseService xypjRemoteBaseService;
    @Autowired
    private CardsService cardsService;

    @Value("${absolutepath}")
    private String absolutepath;
 
    /**
     * 注册用户
     *
     * @param username   用户名
     * @param password   密码
     * @param sjhm       手机号码
     * @param ztmc       主体名称
     * @param bm         编码
     * @param dzyx       电子邮箱
     * @param lxr        联系人
     * @param type       注册类型 C:法人 P：自然人
     * @param fddbr      法定代表人
     * @param fddbrzjhm  法定代表人证件号码
     * @param zjwj       资质文件
     * @param sfzwjFront 身份证文件正面
     * @param sfzwjBack  身份证文件反面
     * @return
     */
    @RequestMapping(value = "/regist.json", method = RequestMethod.POST)
    public RestServiceResult<Object> addUserInfo(String username,
                                                 String password,
                                                 String sjhm,
                                                 String ztmc,
                                                 String bm,
                                                 String dzyx,
                                                 String lxr,
                                                 String type,
                                                 String fddbr,
                                                 String fddbrzjhm,
                                                 MultipartFile zjwj,
                                                 MultipartFile sfzwjFront,
                                                 MultipartFile sfzwjBack) {
        RestServiceResult<Object> result = super.getSuccessRestServiceResult();

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("username", username);
        params.put("type", type);

        //校验账号是否是敏感账户
        if (gatewayUserService.selectUserIsSensitiveAccount(username) > 0) {
            return super.getFailedRestServiceResult("该账号是系统账户,请重新注册");
        }

        //字段校验
        if (gatewayUserService.getUserByTwoPrincipal(params) != null) {
            return super.getFailedRestServiceResult("该账号已被使用");
        }

        String tybm = (String) xypjRemoteBaseService.checkZmtcIsExist(ztmc, bm, type).getData();
        if (null == tybm || tybm.equals("")) {
            if("P".equals(type)){
                return super.getFailedRestServiceResult("身份证号码与真实姓名不吻合，请重新输入");
            }else{
                return super.getFailedRestServiceResult("该信用主体不存在");
            }
        }
        //拼装成GatewayUserEntity实体类
        GatewayUserEntity entity = new GatewayUserEntity(username, password, sjhm, ztmc, bm, dzyx, lxr, type, fddbr,fddbrzjhm, null);

        String tablename ="";
        //自动注册核验，验证成功则审核状态设为T：审核成功
        if(type.equals("C")) {
        	tablename="t_1000000010014_LFsxNK85Kf";
        }else {
        	tablename="t_10000190010_UNJNiQhGny";
        }
        
        Map<String, Object> list = gatewayUserService.checkFromplatform(tablename,entity,type);
       
        if(!list.get("data").equals(0)) {
        	 entity.setShzt("T");
        }else {
        	 //初始审核状态为S：审核中
            entity.setShzt("S");
        }
        //上传文件及大小校验
        if (type.equals("C")) {
            if (null == zjwj) {
                return super.getFailedRestServiceResult("请选择营业执照");
            }

            if (!zjwj.getOriginalFilename().toLowerCase().endsWith(".png") &&
                    !zjwj.getOriginalFilename().toLowerCase().endsWith(".jpeg") &&
                    !zjwj.getOriginalFilename().toLowerCase().endsWith(".jpg")) {
                return super.getFailedRestServiceResult("营业执照仅支持jpg,jpeg,png格式");
            }

            if (zjwj.getSize() > 5 * 1024 * 1024) {
                return super.getFailedRestServiceResult("营业执照大小超过5M");
            }
        }

        if (null == sfzwjFront) {
            return super.getFailedRestServiceResult("请选择身份证正面");
        }

        if (!sfzwjFront.getOriginalFilename().toLowerCase().endsWith(".png") &&
                !sfzwjFront.getOriginalFilename().toLowerCase().endsWith(".jpeg") &&
                !sfzwjFront.getOriginalFilename().toLowerCase().endsWith(".jpg")) {
            return super.getFailedRestServiceResult("身份证正面仅支持jpg,jpeg,png格式");
        }

        if (sfzwjFront.getSize() > 5 * 1024 * 1024) {
            return super.getFailedRestServiceResult("身份证正面大小超过5M");
        }

        if (null == sfzwjBack) {
            return super.getFailedRestServiceResult("请选择身份证反面");
        }

        if (!sfzwjBack.getOriginalFilename().toLowerCase().endsWith(".png") &&
                !sfzwjBack.getOriginalFilename().toLowerCase().endsWith(".jpeg") &&
                !sfzwjBack.getOriginalFilename().toLowerCase().endsWith(".jpg")) {
            return super.getFailedRestServiceResult("身份证反面仅支持jpg,jpeg,png格式");
        }

        if (sfzwjBack.getSize() > 5 * 1024 * 1024) {
            return super.getFailedRestServiceResult("身份证反面大小超过5M");
        }

       
        if (null != entity) {
            try {
                this.setTimes(entity);

                //先把文件存到本地,生成一个uuid序列号文件夹
                String dirPath = absolutepath + File.separator + "xypjUser" + File.separator + UuidUtil.getInstance().getUUid();
                entity.setDirPath(dirPath);

                //存储文件
                if (entity.getType().equals("C")) {
                    gatewayUserService.fileUpload(zjwj, dirPath, "zjwj_");
                    entity.setZjwj("zjwj_" + zjwj.getOriginalFilename());
                }

                gatewayUserService.fileUpload(sfzwjFront, dirPath, "sfzfront_");
                entity.setSfzwj_front("sfzfront_" + sfzwjFront.getOriginalFilename());
                gatewayUserService.fileUpload(sfzwjBack, dirPath, "sfzback_");
                entity.setSfzwj_back("sfzback_" + sfzwjBack.getOriginalFilename());
               
               
                entity.setZhzt("J");

                //默认头像
                String iconPath = dirPath + File.separator + "icon" + File.separator + UuidUtil.getInstance().getUUid();
                if (type.equals("C")) {
                    gatewayUserService.setDefalutIcon(iconPath, "company.png");
                } else {
                    gatewayUserService.setDefalutIcon(iconPath, "person.png");
                }
                entity.setIcon(iconPath + File.separator + "icon.png");

                gatewayUserService.addUserInfo(entity);
            BigInteger bi =    gatewayUserService.getUserInfo(bm);
            long tId = bi.longValue();
                StringBuffer sb1 = new StringBuffer();
                sb1.append(entity.getDirPath())
                  .append(File.separator)
                  .append(entity.getZjwj());
                if (type.equals("C")) {
                    gatewayUserService.addZjPhotoInfo(null, null, "ZZ", sb1.toString(), null, null, tId, null,"2");
                }
                StringBuffer sb2 = new StringBuffer();
                sb2.append(entity.getDirPath())
                  .append(File.separator)
                  .append(entity.getSfzwj_back());
                gatewayUserService.addZjPhotoInfo(null, null, "SF", sb2.toString(), null, null, tId, null,"2");
                StringBuffer sb3 = new StringBuffer();
                sb3.append(entity.getDirPath())
                  .append(File.separator)
                  .append(entity.getSfzwj_front());
                gatewayUserService.addZjPhotoInfo(null, null, "SS", sb3.toString(), null, null, tId, null,"2");
          
                Enterprise enter = new Enterprise();
                enter.setId(String.valueOf(tId));
                cardsService.addReportEnterprise(enter);
                
            } catch (Exception e) {
                result = super.getFailedRestServiceResult("添加失败！");
                ExceptionLogger.error(e);
            }
        }
        return result;
    }

    /**
     * 校验用户名是否存在
     *
     * @param username 用户名
     * @param type     类型: C:法人 P:自然人
     * @return
     */
    @RequestMapping(value = "/checkUserName.json", method = RequestMethod.POST)
    public RestServiceResult<Object> checkUserName(String username, String type) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("username", username);
        params.put("type", type);

        //校验账号是否是敏感账户
        if (gatewayUserService.selectUserIsSensitiveAccount(username) > 0) {
            return super.getFailedRestServiceResult("该账号是系统账户,请重新注册");
        }

        //校验用户名是否存在
        if (gatewayUserService.getUserByTwoPrincipal(params) != null) {
            return super.getFailedRestServiceResult("该账号已被使用");
        }

        return super.getSuccessRestServiceResult();
    }

    /**
     * 校验法人自然人是否存在
     *
     * @param ztmc 主体名称
     * @param bm   编码
     * @param type 类型: C:法人 P:自然人
     * @return
     */
    @RequestMapping(value = "/checkZmtcIsExist.json", method = RequestMethod.POST)
    public RestServiceResult<Object> checkZmtcIsExist(String ztmc,
                                                      String bm,
                                                      String type) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("ztmc", ztmc);
        params.put("type", type);

        if (gatewayUserService.getUserByTwoPrincipal(params) != null) {
            return super.getFailedRestServiceResult("该主体名称已被其他账号使用");
        }

        params.remove("ztmc");
        params.put("bm", bm);
        if (gatewayUserService.getUserByTwoPrincipal(params) != null) {
            return super.getFailedRestServiceResult("该编码已被其他账号使用");
        }

        String tybm = (String) xypjRemoteBaseService.checkZmtcIsExist(ztmc, bm, type).getData();
        if (null == tybm || tybm.equals("")) {
//            if("P".equals(type)){
//                return super.getFailedRestServiceResult("身份证号码与真实姓名不吻合，请重新输入");
//            }else{
//                return super.getFailedRestServiceResult("该信用主体不存在");
//            }
        	return super.getFailedRestServiceResult("该信用主体不存在");
        }

        return super.getSuccessRestServiceResult();
    }

    /**
     * 用户登录
     *
     * @param username 用户名
     * @param password 密码
     * @param type     类型: C:法人 P:自然人
     * @return
     */
    @RequestMapping(value = "/login.json", method = RequestMethod.POST)
    public RestServiceResult<Map<String, Object>> login(String username, String password, String type) {
        RestServiceResult<Map<String, Object>> result = null;
        Map<String, Object> data = null;
        String xypjGatewayToekn = "";
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            result = super.getFailedRestServiceResult("用户名或密码不能为空！");
        } else {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("username", username);
            params.put("type", type);
            GatewayUserEntity user = gatewayUserService.getUserByTwoPrincipal(params);
            if (null == user) {
                result = super.getFailedRestServiceResult("用户名不存在！");
            } else {
                if (!password.equals(user.getPassword())) {
                    return super.getFailedRestServiceResult("密码不正确！");
                }

                if (user.getZhzt().equals("D")) {
                    return super.getFailedRestServiceResult("该账号被冻结！");
                }

                data = new HashMap<String, Object>();
                try {
                    data.putAll(BeanUtil.populateBean2Map(user));
                    data.remove("password");
                    xypjGatewayToekn = JWTHelper.createJWT(String.valueOf(user.getId()), user.getUsername(), XypjConstants.NUMBER_ZERO);
                    data.put(XypjConstants.XYPJ_GATEWAY_TOKEN, xypjGatewayToekn);
                    // 缓存用户会话信息
                    gatewayAuthenticationService.putUserSessionData(xypjGatewayToekn, user);
                } catch (Exception e) {
                    ExceptionLogger.error(e);
                }
                result = super.getSuccessRestServiceResult(data);
            }
        }
        return result;
    }

    /**
     * 用户退出
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/logout.json", method = RequestMethod.POST)
    public RestServiceResult<Object> logout(HttpServletRequest request) {
        RestServiceResult<Object> result = super.getSuccessRestServiceResult();
        String XypjGatewayToken = HttpServletHelper.getUserXypjGatewayToken(request);

        if (StringUtils.isNotBlank(XypjGatewayToken)) {
            try {
                gatewayAuthenticationService.clearUserSessionData(XypjGatewayToken, gatewayAuthenticationService.getCurrentUserInfo(XypjGatewayToken));
                result = super.getSuccessRestServiceResult();
            } catch (Exception e) {
                ExceptionLogger.error(e);
                result = super.getFailedRestServiceResult("用户退出失败！");
            }
        }
        return result;
    }

    /**
     * 得到头像图片
     *
     * @param id       用户id
     * @param response
     * @throws IOException
     */
    @RequestMapping("/getIcon.png")
    public void getIcon(@RequestParam(value = "id", defaultValue = "", required = true) String id,
                        HttpServletResponse response) throws IOException {
        if (null != id && !"".equals(id)) {
            response.setContentType("image/png");
            response.setCharacterEncoding("UTF-8");
            OutputStream outputSream = response.getOutputStream();

            Map<String, Object> params = new HashMap<String, Object>();
            params.put("id", Long.parseLong(id));
            GatewayUserEntity gatewayUserEntity = gatewayUserService.getUserByTwoPrincipal(params);

            InputStream fileInputStream = new FileInputStream(gatewayUserEntity.getIcon());
            byte[] data = this.toByteArray(fileInputStream);
            fileInputStream.close();

            InputStream in = new ByteArrayInputStream(data);
            in.close();
            int len = 0;

            byte[] buf = new byte[1024];
            while ((len = in.read(buf, 0, 1024)) != -1) {
                outputSream.write(buf, 0, len);
            }

            outputSream.close();
        }
    }

    /**
     * 得到证件照头像
     *
     * @param id
     * @param response
     * @throws IOException
     */
    @RequestMapping("/getZjPhoto.png")
    public void getZjPhoto(@RequestParam(value = "id", defaultValue = "", required = true) String id,
                           HttpServletResponse response) throws IOException {
        if (null != id && !"".equals(id)) {
            response.setContentType("image/png");
            response.setCharacterEncoding("UTF-8");
            OutputStream outputSream = response.getOutputStream();

            LinkedHashMap zjPhotoInfo = gatewayUserService.getZjPhotoInfo(Long.parseLong(id));

            InputStream fileInputStream = new FileInputStream((String) zjPhotoInfo.get("filepath"));
            byte[] data = this.toByteArray(fileInputStream);
            fileInputStream.close();

            InputStream in = new ByteArrayInputStream(data);
            in.close();
            int len = 0;

            byte[] buf = new byte[1024];
            while ((len = in.read(buf, 0, 1024)) != -1) {
                outputSream.write(buf, 0, len);
            }

            outputSream.close();
        }
    }

    private byte[] toByteArray(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }

    /**
     * 设置当前时间
     *
     * @param entity
     */
    private void setTimes(GatewayUserEntity entity) {
        Timestamp currentTime = new Timestamp(DateUtils.getCurrentDateTime().getTime());
        entity.setCreateTime(currentTime);
        entity.setUpdateTime(currentTime);
        entity.setDelFlag(1);
    }
}